package com.cmw.udp.l302;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.UUID;

/**
 * UDP 提供者，用于提供服务
 */
public class UDPProvider02 {

    public static void main(String[] args) throws IOException {
        String sn = UUID.randomUUID().toString();
        Provider provider = new Provider(sn);
        provider.start();

        // 读取任意键盘信息后可以退出
        System.in.read();
        provider.exit();
    }

    private static class Provider extends Thread{
        private final String sn;

        private boolean done = false;

        private DatagramSocket ds = null;

        public Provider(String sn) {
            this.sn = sn;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("UDPProvider2 Started.");

            try {
                //监听20000 端口
                ds = new DatagramSocket(20000);

                while (!done){
                    byte[] buf = new byte[512];
                    DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
                    //接收
                    ds.receive(receivePack);

                    //打印接收到的信息与发送都是的信息
                    //ip,port, dataLen, data
                    String ip = receivePack.getAddress().getHostAddress();
                    int port = receivePack.getPort();
                    int dataLen = receivePack.getLength();
                    byte[] dataArr = receivePack.getData();
                    String data = new String(dataArr);
                    System.out.println(String.format("UDPProvider2 receive from ip:%s\t port:%d\t dataLen：%d\t data:%s", ip, port, dataLen, data));

                    //MessageCreator 解析端口
                    int responsePort = MessageCreator.parsePort(data);
                    //如果端口号不等于-1 回送数据到 Client
                    if(-1 != responsePort){
                        //构建一份回送数据
                        String responseData = MessageCreator.buildWithSn(sn);
                        byte[] responseDataByte = responseData.getBytes();
                        DatagramPacket responsePack = new DatagramPacket(responseDataByte, responseDataByte.length,
                                receivePack.getAddress(), responsePort);
                        ds.send(responsePack);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                close();
            }
            System.out.println("UDPProvider2 Finished.");
        }

        private void close(){
            if(null == ds) return;
            ds.close();
            ds = null;
        }

        /**
         * 提供结束
         */
        void exit(){
            done = true;
            close();
        }
    }
}
